﻿/*
	Copyright 2009 CATsoft Development GmbH

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

/*
Main Functions
*/
var COMM;
var mp3t;
var music;
var anim;

var partnertoken;
var sid;

var lastAlbumList;
var lastArtistList;
var lastTrackList;
var lastTokenList;
var lastPlayList;
var lastList;
var lastArtist;
var Listdepth;
var listboxChanged;;

/**************************************************************
	Initialize Gadget
*************************************************************/
function Init() {
	partnertoken = "2989248581";
	sid=null;
	resetLists();
	COMM = new comm();
	mp3t = new mp3tunes();
	music = new music();
	anim = new animate();

	pluginHelper.onAddCustomMenuItems = onAddCustomMenuItems;

// restore saved options
	if(options.exists("Password") && options.exists("Username"))
		mp3t.mp3_login(options.getValue("Username"), options.getValue("Password"));
	if(options.exists("Red") && options.exists("Green") && options.exists("Blue")){
		anim.changeBgcolor(options.getValue("Red"), options.getValue("Green"), options.getValue("Blue"));
	} else {
		options.putDefaultValue("Red", 0);
		options.putDefaultValue("Green", 0);
		options.putDefaultValue("Blue", 0);
	}
	if(options.exists("Opacity"))
		anim.setOpacity(255 - options.getValue("Opacity"));
	if(options.exists("Volume")){
		sbVolume.value = options.getValue("Volume");
	}else{
		options.putDefaultValue("Volume", -3000);
		sbVolume.value = -3000;
	}
}

/**************************************************************
	fires when a option was changed
*************************************************************/
function onOptionChanged(){
	if(event.propertyName == "Password"){
		sid = null;
		mp3t.mp3_login(options.getValue("Username"), options.getValue("Password"));
	}

	if(event.propertyName == "Opacity"){
		anim.setOpacity(255 - options.getValue("Opacity"));
	}

	if(event.propertyName == "Blue" || event.propertyName == "Green" || event.propertyName == "Red"){
		anim.changeBgcolor(options.getValue("Red"), options.getValue("Green"), options.getValue("Blue"));
	}
}

/**************************************************************
	removes all entries in all lists
*************************************************************/
function resetLists(){
	returnObj = null;
	lastAlbumList = null;
	lastArtistList = null;
	lastTrackList = null;
	lastTokenList = null;
	lastPlayList = null;
	lastList = null;
	lbxMainItems = 0;
	
}

/**************************************************************
	display all main elements after login
*************************************************************/
function loggedIn(successful){
	if(music.curAudioClip != null)
		music.stopTrack();
	hideBack();
	dvButtons.visible = false;
	pbSong.visible = false;
	resetLists();
	hideListbox();
	lbxMain.removeAllElements();
	if(successful){
		lblInfoText.innerText = SELECT_CATEGORY;
		dvSelectList.visible = true;
		dvButtons.visible = true;
	} else {
		lblInfoText.innerText = LOGIN_FIRST;
		dvSelectList.visible = false;
		dvButtons.visible = false;
	}
	lblInfoText.visible = true;
	imgMp3tunes.visible = true;
}

function hideListbox(){
	dvMain.visible = false;
}

function showListbox(){
	lblInfoText.visible = false;
	dvMain.visible = true;
	imgMp3tunes.visible = false;
	}

/**************************************************************
	start object request depending witch button was clicked
*************************************************************/
function showSelection(selection){
	anim.startLodingAnimation();
	hideAlbumArt(30000); // if an albumart is playing stop it and wait for 30 sec. to reapear
	Listdepth = 0;
	lastList = "";
	lastArtist = "";
	hideBack();

	if(sid != null){
		if(selection == 0){
			mp3t.mp3_getLockerData("artist","","","","","","","","showArtists");
		} else if(selection == 1){
			mp3t.mp3_getLockerData("album","","","","","","","","showAlbums");
		} else if(selection == 2){
			mp3t.mp3_getLockerData("track_token","","","","","","","","showTrackToken");
		} else if(selection == 3){
			mp3t.mp3_getLockerData("playlist","","","","","","","","showPlaylists");
		}
	} else {
		alert(LOGIN_FIRST);
	}
}

/**************************************************************
	display retrived tocken and max. number of  tracks
*************************************************************/
function showTrackToken(obj){
	
// save obj for later reuse
	lastTokenList = obj;

	lbxMain.removeAllElements();

	if(obj.summary.totalResults > 0){
	var length = obj.tokenList.length;

	// add show alltracks element
		var totalTracks = 0;
		for(var i = 0; i < length; i++){
			totalTracks = totalTracks + parseInt(obj.tokenList[i].count);
		}
		lbxEntry = "<item height=\"20\" onclick=\"getTrackbyToken('playAll');\"><label font=\"tahoma\" size=\"10\">" + ALL_TRACKS +" (" + totalTracks + ")</label></item>";
		lbxMain.appendElement(lbxEntry);

		
		for(var i = 0; i<length; i++){

		//create entry and add it
			lbxEntry = "<item height=\"20\" onclick=\"getTrackbyToken('" + obj.tokenList[i].token +  "');\"><label font=\"tahoma\" size=\"10\">" + obj.tokenList[i].token  +" (" + obj.tokenList[i].count +")</label></item>";
			lbxMain.appendElement(lbxEntry);
			anim.lbxMainItems = i;
		}
	} else {
		lbxEntry = "<item height=\"20\" enabled=\"false\"><label font=\"tahoma\" size=\"10\" italic=\"true\">" + NO_ENTRY + "</label></item>";
		lbxMain.appendElement(lbxEntry);
		anim.lbxMainItems = 1;
	}
	anim.lbxMainItems = length;

	finishDisplaying();

}

/**************************************************************
	retrive tracks of selected token
*************************************************************/
function getTrackbyToken(token){
	if(token != "playAll"){
		lastList = "TrackToken"
		lblBack.tooltip = token;
		lblBack.innerText = token;
		anim.startLodingAnimation();
		mp3t.mp3_getLockerData("track", "", "", "", "", "", token,"","showTracks");
		showBack();
	} else {
		anim.startLodingAnimation();
		mp3t.mp3_getLockerData("track", "", "", "", "", "", "","","showTracks");
	}
}

/**************************************************************
	display retrived tracks
*************************************************************/
function showTracks(obj){

// save obj for later reuse
	lastTrackList = obj;
	var tL = obj.trackList;

	lbxMain.removeAllElements();

	if(obj.summary.totalResults > 0){
		var length = obj.trackList.length;
		obj.trackList.sort(sortByTrackTitle);

		for(var i = 0; i<length; i++){

		// get tracklength and compute minutes and seconds from it
		var trackTime = computeLength(obj.trackList[i].trackLength);

		// remove escape chars from artist Name
		var artistName = replaceEscape(obj.trackList[i].artistName);

		// remove escape chars from Playtitle
			var trackTitle = replaceEscape(obj.trackList[i].trackTitle);

		//create entry and add it
			lbxEntry = "<item height=\"20\" onclick=\"playTrackInit(" + i +  ");\" tooltip=\"by " + artistName + "\"><label font=\"tahoma\" size=\"10\">" + trackTitle +" (" + trackTime +")</label></item>";
			lbxMain.appendElement(lbxEntry);
			anim.lbxMainItems = i;
		}
	} else {
		lbxEntry = "<item height=\"20\" enabled=\"false\"><label font=\"tahoma\" size=\"10\" italic=\"true\">" + NO_ENTRY + "</label></item>";
		lbxMain.appendElement(lbxEntry);
		anim.lbxMainItems = 1;
	}

	finishDisplaying();
}

/**************************************************************
	display retrived artists
*************************************************************/
function showArtists(obj){
	hideBack();					 //only selection in select list so always hide backbutton

//save obj for later reuse
	lastArtistList = obj;

	lbxMain.removeAllElements();

	if(obj.summary.totalResults > 0){
		var length = obj.artistList.length;
		obj.artistList.sort(sortByArtistName);

		for(var i = 0; i<length; i++){

		// remove escape chars from Playtitle
			var name = replaceEscape(obj.artistList[i].artistName);

		// create entry and add it
			lbxEntry = "<item height=\"20\" onclick=\"getArtistAlbums(" + obj.artistList[i].artistId+ ",'"  + name + "')\"><label font=\"tahoma\" size=\"10\">"+ name+"</label></item>";
			lbxMain.appendElement(lbxEntry);
			anim.lbxMainItems = i;
		}
	} else {
		lbxEntry = "<item height=\"20\" enabled=\"false\"><label font=\"tahoma\" size=\"10\" italic=\"true\">" + NO_ENTRY + "</label></item>";
		lbxMain.appendElement(lbxEntry);
		anim.lbxMainItems = 1;
	}

	finishDisplaying();
}

/**************************************************************
	retrive tracks of selected artist
*************************************************************/
function getArtistAlbums(artistId, artistName){
	Listdepth = 1;
	lastList = "Artist"
	lblBack.tooltip = artistName;
	lastArtist = artistName;
	lblBack.innerText = ARTIST;
	anim.startLodingAnimation();
	mp3t.mp3_getLockerData("album", "", "", "", artistId, "", "","","showAlbums");
	showBack();
}

/**************************************************************
	display retrived albums
*************************************************************/
function showAlbums(obj){
	if(Listdepth == 0){
		hideBack();
	}

// save obj for late reuse
	lastAlbumList = obj;

	lbxMain.removeAllElements();

	if(obj.summary.totalResults > 0){
		var length = obj.albumList.length;
		obj.albumList.sort(sortByAlbumTitle);

		for(var i = 0; i < length; i++){

			var name = replaceEscape(obj.albumList[i].artistName);

			var albumTitle = replaceEscape(obj.albumList[i].albumTitle);

		//create entry and add it
			lbxEntry =  "<item height=\"20\" onclick=\"getAlbumTracks(" + obj.albumList[i].albumId+ ",'" + albumTitle + "')\" tooltip=\"by " +name +"\"><label  font=\"tahoma\" size=\"10\">"+ albumTitle+"</label></item>";
			lbxMain.appendElement(lbxEntry);
			anim.lbxMainItems = i;
		}
	} else {
		lbxEntry = "<item height=\"20\" enabled=\"false\"><label font=\"tahoma\" size=\"10\" italic=\"true\">" + NO_ENTRY + "</label></item>";
		lbxMain.appendElement(lbxEntry);
		anim.lbxMainItems = 1;
	}

	finishDisplaying();
}

/**************************************************************
	retrive tracks of selected album
*************************************************************/
function getAlbumTracks(albumId, albumName){
	lastList = "Album";
	if(Listdepth == 0){
		lblBack.innerText = ALBUM;
		lblBack.tooltip = albumName;
	} else if(Listdepth == 1) {
		lblBack.innerText = ARTIST + " < " + ALBUM;
		lblBack.tooltip = lastArtist + " / " + albumName;
	}
	anim.startLodingAnimation();
	mp3t.mp3_getLockerData("track", "", "", albumId, "", "","", "","showTracks");
	showBack();
}

/**************************************************************
	display retrived playlists
*************************************************************/
function showPlaylists(obj){
	hideBack();

//save obj for later reuse
	lastPlayList = obj;

	lbxMain.removeAllElements();

	if(obj.summary.totalResults > 0){
		var length = obj.playlistList.length;
		obj.playlistList.sort(sortByPlaylistTitle);

		for(var i = 0; i < length; i++){
			
		//create entry and add it
			lbxEntry =  "<item height=\"20\" onclick=\"getPlaylistTracks(" + i + ",'" +  obj.playlistList[i].playlistTitle + "')\"><label  font=\"tahoma\" size=\"10\">"+ obj.playlistList[i].playlistTitle+"</label></item>";
			lbxMain.appendElement(lbxEntry);
			anim.lbxMainItems = i;
		}
	} else {
		lbxEntry = "<item height=\"20\" enabled=\"false\"><label font=\"tahoma\" size=\"10\" italic=\"true\">" + NO_ENTRY + "</label></item>";
		lbxMain.appendElement(lbxEntry);
		anim.lbxMainItems = 1;
	}

	finishDisplaying();
}

/**************************************************************
	retrive tracks of selected playlist
*************************************************************/
function getPlaylistTracks(listNo, listName){
	lastList = "Playlist";
	lblBack.innerText = PLAYLIST;
	lblBack.tooltip = listName;
	anim.startLodingAnimation();
	var playlistId = lastPlayList.playlistList[listNo].playlistId;
	mp3t.mp3_getLockerData("track", "", "", "", "", playlistId, "","","showTracks");
	showBack();
}

/**************************************************************
	enable scrolling in listbox and stop loding animation
*************************************************************/
function finishDisplaying(){
	listboxChanged = true;
	anim.lbxScroll();
	showListbox();
	anim.stopLodingAnimation();
}

/**************************************************************
	show/hide backbutton and label
*************************************************************/
function showBack(){
	dvBack.visible = true;
}

function hideBack(){
	dvBack.visible = false;
}

/**************************************************************
	go back to last list
*************************************************************/
function toLastList(){
	hideAlbumArt(30000);
	if(lastList == "Album"){
		if(Listdepth == 1){
			lastList = "Artist";
			lblBack.tooltip = lastArtist;
			lblBack.innerText = ARTIST;
		} else {
			artistLength = 0;
			lastList = "";
		}
		showAlbums(lastAlbumList);
	} else if(lastList == "Artist"){
		showArtists(lastArtistList);
		lastList = "";
	} else if(lastList == "Playlist"){
		showPlaylists(lastPlayList);
		lastList = "";
	} else if(lastList == "TrackToken"){
		showTrackToken(lastTokenList);
		lastList = "";
	}
}

/***********************************************************************
	Change menu
***********************************************************************/
function onAddCustomMenuItems(menu) 
{
  menu.AddItem(UPDATE_CHECK, 0, runcheckupdate);
  function runcheckupdate() { checkUpdate(true) }
	menu.AddItem(NEW_ACCOUNT, 0, runnewaccount);
}

function runnewaccount(){
	detailsView = new DetailsView();

	detailsView.SetContent( "", undefined, "newaccount.xml", false, 0);
	detailsView.detailsViewData.putValue( "closeDetailsView", closeDetailsView);
	plugin.ShowDetailsView(detailsView,  "",  gddDetailsViewFlagNone, onNewaccountViewFeedback);  
}

/***********************************************************************
	Check for Updates
***********************************************************************/
function checkUpdate(manualrequest)
{
	var today = new Date();

	if( !manualrequest)
	{
		var lastcheck = options.getValue("lastcheck");
		if( lastcheck + 86400000 >  today.getTime())
				return;
	}
	else
		view.setTimeout( "checkUpdate(false)", 86400000);		// Come back one day later

	var version = '';
	var parser = COMM.sendXMLHttpRequest( "http://www.catsoft.ch/gg/mp3versioninfo.xml" );

	if (parser)
	{
		if( parser.checkError(false).length == 0 ) 
		{
			version = parser.getValue("version");
			if(version > GADGET_VERSION)
			{
				detailsView = new DetailsView();
		
				detailsView.SetContent(  "", undefined,  "newversion.xml",  false, 0 );
				detailsView.detailsViewData.putValue( "closeDetailsView", closeDetailsView);
				detailsView.detailsViewData.putValue( "version", version);
				detailsView.detailsViewData.putValue( "description", parser.getValue("description"));
				detailsView.detailsViewData.putValue( "link", parser.getValue("link"));
				plugin.ShowDetailsView(detailsView,  "",  gddDetailsViewFlagNone, onVersionViewFeedback);  
			}
				//if there is no update, and the user has manually asked tell them
			else if(manualrequest) //Once again, this will be explained later.
			{
				alert(CURRENT_VERSION);
			}

			options.putValue("lastcheck", today.getTime());
		}
	}
}

/***********************************************************************
	Close HTML Detail view
***********************************************************************/
function closeDetailsView() {
  plugin.CloseDetailsView();
}

/***********************************************************************
	return from version view
***********************************************************************/
function onVersionViewFeedback(detailsViewFlags) {
}

/***********************************************************************
	return from new account view
***********************************************************************/
function onNewaccountViewFeedback(detailsViewFlags) {
}